package com.viking.web;

import com.viking.car.*;

import java.io.IOException;
import java.net.Socket;
import java.util.Random;


public class DispatcherServlet extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {

        String ip = request.getParameter("ip");
        int port = Integer.parseInt(request.getParameter("port"));
        String type = request.getParameter("type");
        String orderNo = request.getParameter("orderNo");
        String userId = request.getParameter("userId");
        String carId = request.getParameter("carId");
        String orderStartDt = request.getParameter("orderStartDt");
        String orderStartDtOff = request.getParameter("orderStartDtOff");
        String orderEndDt = request.getParameter("orderEndDt");
        String orderEndDtOff = request.getParameter("orderEndDtOff");
        int commandId= Integer.parseInt(request.getParameter("commandId"));
        System.out.println("commandId="+commandId);
        Socket socket = new Socket(ip,port);
        Token token = new Token();
        token.setType(type);
        token.setOrderNo(orderNo);
        token.setUserId(userId);
        token.setCarId(carId);
        token.setOrderStartDt(orderStartDt);
        token.setOrderStartDtOff(orderStartDtOff);
        token.setOrderEndDt(orderEndDt);
        token.setOrderEndDtOff(orderEndDtOff);

        int seqId = new Random().nextInt(100000000);
        int cid = choseCommandId(commandId);
        Message req = MessageUtils.generateMessage(token.toString(), commandId, seqId,false);
        request.setAttribute("req",req);
//        Message resp = Client.executeCommand(socket, token.toString(), seqId, cid);
        Message resp = Client.executeCommand2(ip,port, token.toString(), seqId, cid);
        request.setAttribute("resp",resp);
        request.getRequestDispatcher("/result.jsp").forward(request,response);
    }


    private int choseCommandId(int commandId) {
        switch (commandId){
            case 1:
                return Constants.TAKE_CAR;
            case 2:
                return Constants.OPEN_DOOR;
            case 3:
                return Constants.LOCK_DOOR;
            case 4:
                return Constants.RETURN_CAR;
            case 5:
                return Constants.QUERYPOWER;
        }
        return Constants.TAKE_CAR;
    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        this.doPost(request,response);
    }
}
